package com.tjetc.utils;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import okhttp3.ConnectionPool;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.ConcurrentReferenceHashMap;

import java.util.Map;
import java.util.concurrent.TimeUnit;

public class AiUtils {

    private static final String DEEPSEEK_API_KEY = "sk-221e51b7414d457993a6a9dbeff3bd45";
    private static OkHttpClient httpClient;
    @Qualifier("clusterRedisTemplate")
    private static RedisTemplate<String,Object> clusterRedisTemplate;
//    private static  Map<String,Object> map=new ConcurrentReferenceHashMap<>();
    static {
        httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES))
                .build();
    }

    // 私有构造函数，防止实例化
    private AiUtils() {
        throw new IllegalStateException("Utility class");
    }

    public static String chat(String message) throws Exception {
        if (DEEPSEEK_API_KEY == null || DEEPSEEK_API_KEY.isEmpty()) {
            throw new IllegalStateException("DeepSeek API key is not configured");
        }

        // 构建请求体
        String requestBody = buildRequestBody(message);

        Request request = new Request.Builder()
                .url("https://api.deepseek.com/chat/completions")
                .post(RequestBody.create(
                        MediaType.parse("application/json"),
                        requestBody))
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + DEEPSEEK_API_KEY)
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("API request failed: " + response.code() + " - " + response.message());
            }

            String responseBody = response.body().string();
            // 这里可以添加JSON解析，提取需要的内容
            JsonObject jsonObject=JsonParser.parseString(responseBody).getAsJsonObject();
//            System.out.println("jsonObject = " + jsonObject);
//            System.out.println("jsonObject.get(\"choices\").getAsString() = " + jsonObject.get("choices").getAsString());

                // 提取AI回复内容
                String aiContent = jsonObject.get("choices").getAsJsonArray().get(0).getAsJsonObject()
                        .get("message").getAsJsonObject()
                        .get("content").getAsString();
//                System.out.println("AI回复内容: " + aiContent);
                return aiContent;


        }
    }

    private static String buildRequestBody(String userMessage) {
        return String.format("""
            {
              "messages": [
                {
                  "content": "你是秀动APP的官方客服",
                  "role": "system"
                },
                {
                  "content": "%s",
                  "role": "user"
                }
              ],
                            "model": "deepseek-chat",
              "temperature": 0.3,
              "max_tokens": 800,
              "top_p": 0.9,
              "frequency_penalty": 0.0,
              "presence_penalty": 0.0
            }
            """, escapeJson(userMessage));
    }

    private static String escapeJson(String input) {
        return input.replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r");
    }
}
